package stark.app.webserver;

import android.Manifest;
import android.os.Bundle;
import android.widget.TextView;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import stark.app.R;
import stark.common.basic.utils.LogUtil;

public class WebServerActivity extends AppCompatActivity implements WebServerManager.WebServerManagerCallback {

    WebServerManager mServer;
    private TextView mTvAddress;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webserver);
        mServer = WebServerManager.shared();
        mServer.startServer(this, this);

        mTvAddress = findViewById(R.id.tv_address);

        reqPermission();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mServer.stopServer(this);
    }


    @Override
    public void onServerStart(String ip) {
        LogUtil.e(ip);
        mTvAddress.setText(ip + ":"+WebServerService.SERVER_PORT);
    }

    @Override
    public void onServerError(String error) {
        LogUtil.e(error);
        mTvAddress.setText(error);
    }

    @Override
    public void onServerStop() {
    }

    private void reqPermission() {
        PermissionUtils.permission(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .callback(new PermissionUtils.SingleCallback() {
                            @Override
                            public void callback(boolean isAllGranted, @NonNull List<String> granted, @NonNull List<String> deniedForever, @NonNull List<String> denied) {
                                if (!isAllGranted) {
                                    ToastUtils.showShort("未授予权限");
                                }
                            }
                        })
                        .request();
    }
}
